package com.atguigu.msmservice.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.atguigu.msmservice.constant.SessionConstEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author panghl
 * @Date 2021/2/3 13:08
 * @Description TODO
 **/
@RestController
@RequestMapping("/code")
@Api(tags = {"验证码管理"})
public class CodeController {

    /**
     * 图片默认宽度
     */
    private int imgWidth = 100;

    /**
     * 图片默认高度
     */
    private int imgHeight = 50;

    /**
     * 返回验证码图片
     *
     * @param req
     *            HttpServletRequest对象
     * @param res
     *            HttpServletResponse 对象
     * @throws ServletException
     *             异常处理
     * @throws IOException
     *             异常处理
     */
    @ApiOperation(value = "返回验证码图片")
    @GetMapping(produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] index(HttpServletRequest req, HttpServletResponse res, HttpSession session) throws IOException {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(imgWidth, imgHeight, 4, 10);
        // 将认证码存入SESSION
        session.setAttribute(SessionConstEnum.CODE_SESSION.toString(),  captcha.getCode());

        return captcha.getImageBytes();
    }

}
